//
//  YHComposeTextView.swift
//  XLWB
//
//  Created by key on 16/7/3.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class YHComposeTextView: UITextView {

    //接收外界设置placeholder
    var placeholder: String? {
        
        didSet {
            
            placeholderLabel.text = placeholder
            
        }
    }
    
    
    
    //MARK: - 入口
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        
        super.init(frame: frame, textContainer: textContainer)
        
        //添加子控件
        addChildView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    //MARK: - 添加子控件
    func addChildView() {
        
        //添加
        addSubview(placeholderLabel)
        
        //约束
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(self).offset(8)
            make.leading.equalTo(self).offset(5)
            make.width.equalTo(screenW - 10)
            
        }
        
        //MARK: - 通知监听 composeTextView 的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "composeTextViewChangeAction", name: UITextViewTextDidChangeNotification, object: nil)
        
    }
    
    //监听到改变 做出的响应
    func composeTextViewChangeAction() {
        
        //隐藏占位控件
        placeholderLabel.hidden = self.hasText()
        
    }
    
    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    
    
    //MARK: - 懒加载label 背景占位
    private lazy var placeholderLabel: UILabel = {
       
        let lab = UILabel()

        lab.font = UIFont.systemFontOfSize(12)
        
        lab.textColor = UIColor.grayColor()
        
        lab.numberOfLines = 0
        
        return lab
        
    }()
    
}
